<template>
  <div class="performance-monitor">
    <!-- 性能概览卡片 -->
    <el-row :gutter="20" class="performance-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="performance-card">
          <template #header>
            <div class="card-header">
              <span>系统响应时间</span>
              <el-tag :type="getResponseTimeTagType(performance.avgResponseTime)">
                {{ performance.avgResponseTime }}ms
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-chart" ref="responseTimeChartRef"></div>
            <div class="metric-trend">
              <span>较上周</span>
              <span :class="getTrendClass(performance.responseTimeTrend)">
                {{ performance.responseTimeTrend }}%
                <el-icon>
                  <component :is="getTrendIcon(performance.responseTimeTrend)" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="performance-card">
          <template #header>
            <div class="card-header">
              <span>系统吞吐量</span>
              <el-tag :type="getThroughputTagType(performance.throughput)">
                {{ performance.throughput }} TPS
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-chart" ref="throughputChartRef"></div>
            <div class="metric-trend">
              <span>较上周</span>
              <span :class="getTrendClass(performance.throughputTrend)">
                {{ performance.throughputTrend }}%
                <el-icon>
                  <component :is="getTrendIcon(performance.throughputTrend)" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="performance-card">
          <template #header>
            <div class="card-header">
              <span>错误率</span>
              <el-tag :type="getErrorRateTagType(performance.errorRate)">
                {{ performance.errorRate }}%
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-chart" ref="errorRateChartRef"></div>
            <div class="metric-trend">
              <span>较上周</span>
              <span :class="getTrendClass(-performance.errorRateTrend)">
                {{ performance.errorRateTrend }}%
                <el-icon>
                  <component :is="getTrendIcon(-performance.errorRateTrend)" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="performance-card">
          <template #header>
            <div class="card-header">
              <span>资源使用率</span>
              <el-tag :type="getResourceUsageTagType(performance.resourceUsage)">
                {{ performance.resourceUsage }}%
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-chart" ref="resourceUsageChartRef"></div>
            <div class="metric-trend">
              <span>较上周</span>
              <span :class="getTrendClass(-performance.resourceUsageTrend)">
                {{ performance.resourceUsageTrend }}%
                <el-icon>
                  <component :is="getTrendIcon(-performance.resourceUsageTrend)" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 性能分析图表 -->
    <el-row :gutter="20" class="performance-charts">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>系统调用分布</span>
              <el-radio-group v-model="distributionTimeRange" size="small">
                <el-radio-button label="hour">1小时</el-radio-button>
                <el-radio-button label="day">24小时</el-radio-button>
                <el-radio-button label="week">7天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="distributionChartRef"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>性能瓶颈分析</span>
              <el-select v-model="bottleneckType" size="small">
                <el-option label="响应时间" value="response" />
                <el-option label="吞吐量" value="throughput" />
                <el-option label="错误率" value="error" />
                <el-option label="资源使用" value="resource" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="bottleneckChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 优化建议列表 -->
    <el-card shadow="hover" class="optimization-card">
      <template #header>
        <div class="card-header">
          <span>优化建议</span>
          <div class="header-operations">
            <el-button type="primary" link @click="handleRefreshSuggestions">
              刷新
            </el-button>
            <el-button type="primary" link @click="handleExportSuggestions">
              导出
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="suggestionList" border v-loading="suggestionLoading">
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getSuggestionTypeTag(row.type)">
              {{ getSuggestionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTag(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="建议标题" min-width="200" />
        <el-table-column prop="description" label="建议描述" min-width="300" />
        <el-table-column prop="impact" label="影响程度" width="120">
          <template #default="{ row }">
            <el-progress
              :percentage="row.impact"
              :status="getImpactStatus(row.impact)"
              :stroke-width="15"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getSuggestionStatusTag(row.status)">
              {{ getSuggestionStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewSuggestionDetail(row)">
              详情
            </el-button>
            <el-button type="primary" link @click="handleApplySuggestion(row)">
              应用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="suggestionPage"
          v-model:page-size="suggestionPageSize"
          :total="suggestionTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSuggestionPageSizeChange"
          @current-change="handleSuggestionPageChange"
        />
      </div>
    </el-card>

    <!-- 建议详情对话框 -->
    <el-dialog
      v-model="suggestionDetailVisible"
      title="优化建议详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="建议类型">
          <el-tag :type="getSuggestionTypeTag(currentSuggestion.type)">
            {{ getSuggestionTypeLabel(currentSuggestion.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag :type="getPriorityTag(currentSuggestion.priority)">
            {{ getPriorityLabel(currentSuggestion.priority) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="建议标题">
          {{ currentSuggestion.title }}
        </el-descriptions-item>
        <el-descriptions-item label="影响程度">
          <el-progress
            :percentage="currentSuggestion.impact"
            :status="getImpactStatus(currentSuggestion.impact)"
            :stroke-width="15"
          />
        </el-descriptions-item>
        <el-descriptions-item label="建议描述" :span="2">
          {{ currentSuggestion.description }}
        </el-descriptions-item>
        <el-descriptions-item label="优化方案" :span="2">
          {{ currentSuggestion.solution }}
        </el-descriptions-item>
        <el-descriptions-item label="预期效果" :span="2">
          {{ currentSuggestion.expectedResult }}
        </el-descriptions-item>
        <el-descriptions-item label="实施步骤" :span="2">
          <el-steps direction="vertical" :active="currentSuggestion.steps?.length">
            <el-step
              v-for="(step, index) in currentSuggestion.steps"
              :key="index"
              :title="step.title"
              :description="step.description"
            />
          </el-steps>
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button @click="suggestionDetailVisible = false">关闭</el-button>
        <el-button
          v-if="currentSuggestion.status === 'pending'"
          type="primary"
          @click="handleApplySuggestion(currentSuggestion)"
        >
          应用建议
        </el-button>
      </template>
    </el-dialog>

    <!-- 应用建议对话框 -->
    <el-dialog
      v-model="applySuggestionVisible"
      title="应用优化建议"
      width="500px"
    >
      <el-form
        ref="applyFormRef"
        :model="applyForm"
        :rules="applyRules"
        label-width="100px"
      >
        <el-form-item label="实施时间" prop="applyTime">
          <el-date-picker
            v-model="applyForm.applyTime"
            type="datetime"
            placeholder="请选择实施时间"
          />
        </el-form-item>
        <el-form-item label="实施人" prop="operator">
          <el-input v-model="applyForm.operator" placeholder="请输入实施人" />
        </el-form-item>
        <el-form-item label="实施备注" prop="remark">
          <el-input
            v-model="applyForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入实施备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="applySuggestionVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApplySuggestion" :loading="applying">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 性能报告对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="性能报告"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-loading="reportLoading">
        <template v-if="currentReport">
          <!-- 报告摘要 -->
          <el-card class="report-section">
            <template #header>
              <div class="card-header">
                <span>报告摘要</span>
                <el-button type="primary" link @click="handleExportReport">
                  导出报告
                </el-button>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="生成时间">
                {{ new Date(currentReport.timestamp).toLocaleString() }}
              </el-descriptions-item>
              <el-descriptions-item label="总体评分">
                <el-progress
                  :percentage="Math.round(
                    (currentReport.analysis.performance.score +
                    currentReport.analysis.api.score +
                    currentReport.analysis.resources.score +
                    currentReport.analysis.memory.score) / 4
                  )"
                  :status="getScoreStatus(
                    (currentReport.analysis.performance.score +
                    currentReport.analysis.api.score +
                    currentReport.analysis.resources.score +
                    currentReport.analysis.memory.score) / 4
                  )"
                />
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 性能分析 -->
          <el-card class="report-section">
            <template #header>
              <div class="card-header">
                <span>性能分析</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="analysis-item">
                  <div class="analysis-title">页面加载性能</div>
                  <el-progress
                    :percentage="currentReport.analysis.performance.score"
                    :status="getScoreStatus(currentReport.analysis.performance.score)"
                  />
                  <div class="analysis-issues" v-if="currentReport.analysis.performance.issues.length">
                    <div class="issue-title">问题：</div>
                    <ul>
                      <li v-for="issue in currentReport.analysis.performance.issues" :key="issue">
                        {{ issue }}
                      </li>
                    </ul>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="analysis-item">
                  <div class="analysis-title">API 调用性能</div>
                  <el-progress
                    :percentage="currentReport.analysis.api.score"
                    :status="getScoreStatus(currentReport.analysis.api.score)"
                  />
                  <div class="analysis-issues" v-if="currentReport.analysis.api.issues.length">
                    <div class="issue-title">问题：</div>
                    <ul>
                      <li v-for="issue in currentReport.analysis.api.issues" :key="issue">
                        {{ issue }}
                      </li>
                    </ul>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="analysis-item">
                  <div class="analysis-title">资源加载性能</div>
                  <el-progress
                    :percentage="currentReport.analysis.resources.score"
                    :status="getScoreStatus(currentReport.analysis.resources.score)"
                  />
                  <div class="analysis-issues" v-if="currentReport.analysis.resources.issues.length">
                    <div class="issue-title">问题：</div>
                    <ul>
                      <li v-for="issue in currentReport.analysis.resources.issues" :key="issue">
                        {{ issue }}
                      </li>
                    </ul>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="analysis-item">
                  <div class="analysis-title">内存使用性能</div>
                  <el-progress
                    :percentage="currentReport.analysis.memory.score"
                    :status="getScoreStatus(currentReport.analysis.memory.score)"
                  />
                  <div class="analysis-issues" v-if="currentReport.analysis.memory.issues.length">
                    <div class="issue-title">问题：</div>
                    <ul>
                      <li v-for="issue in currentReport.analysis.memory.issues" :key="issue">
                        {{ issue }}
                      </li>
                    </ul>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 优化建议 -->
          <el-card class="report-section">
            <template #header>
              <div class="card-header">
                <span>优化建议</span>
              </div>
            </template>
            <el-timeline>
              <el-timeline-item
                v-for="recommendation in currentReport.recommendations"
                :key="recommendation.title"
                :type="getRecommendationType(recommendation.priority)"
                :timestamp="recommendation.priority"
              >
                <h4>{{ recommendation.title }}</h4>
                <p>{{ recommendation.description }}</p>
                <div class="recommendation-impact">
                  影响程度：
                  <el-progress
                    :percentage="recommendation.impact"
                    :status="getImpactStatus(recommendation.impact)"
                    :stroke-width="15"
                  />
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  getSystemPerformanceData,
  getSystemMonitorData,
  getSystemTrendData,
  getPerformanceSuggestions,
  applyPerformanceSuggestion,
  exportPerformanceSuggestions
} from '@/api/message'
import { usePerformance } from '@/utils/performance'
import { usePerformanceMetrics } from '@/utils/performance-metrics'

// 性能数据
const performance = reactive({
  avgResponseTime: 0,
  responseTimeTrend: 0,
  throughput: 0,
  throughputTrend: 0,
  errorRate: 0,
  errorRateTrend: 0,
  resourceUsage: 0,
  resourceUsageTrend: 0
})

// 图表相关
const responseTimeChartRef = ref(null)
const throughputChartRef = ref(null)
const errorRateChartRef = ref(null)
const resourceUsageChartRef = ref(null)
const distributionChartRef = ref(null)
const bottleneckChartRef = ref(null)
let responseTimeChart = null
let throughputChart = null
let errorRateChart = null
let resourceUsageChart = null
let distributionChart = null
let bottleneckChart = null
const distributionTimeRange = ref('hour')
const bottleneckType = ref('response')

// 建议列表相关
const suggestionList = ref([])
const suggestionLoading = ref(false)
const suggestionPage = ref(1)
const suggestionPageSize = ref(10)
const suggestionTotal = ref(0)

// 建议详情相关
const suggestionDetailVisible = ref(false)
const currentSuggestion = ref({})
const applySuggestionVisible = ref(false)
const applyFormRef = ref(null)
const applyForm = reactive({
  applyTime: '',
  operator: '',
  remark: ''
})
const applying = ref(false)

// 表单验证规则
const applyRules = {
  applyTime: [
    { required: true, message: '请选择实施时间', trigger: 'change' }
  ],
  operator: [
    { required: true, message: '请输入实施人', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入实施备注', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 在 setup 中添加性能优化工具
const {
  loading: performanceLoading,
  error: performanceError,
  loadDataWithCache,
  optimizeChart,
  preloadData,
  executePreload,
  cleanup
} = usePerformance()

// 在 setup 中添加性能指标收集器
const {
  isCollecting,
  startCollection,
  stopCollection,
  getMetrics,
  getHistory,
  generateReport
} = usePerformanceMetrics()

// 添加性能指标数据
const metrics = reactive({
  pageLoad: {},
  apiCalls: {},
  resources: {},
  memory: {},
  fps: {}
})

// 添加性能报告对话框
const reportDialogVisible = ref(false)
const currentReport = ref(null)
const reportLoading = ref(false)

// 初始化
onMounted(() => {
  initCharts()
  loadPerformanceData()
  loadSuggestionList()
  startCollection() // 开始收集性能指标
  
  // 定时刷新数据
  const timer = setInterval(() => {
    loadPerformanceData()
    // 更新性能指标数据
    Object.assign(metrics, getMetrics())
  }, 60000) // 每分钟刷新一次
  
  onUnmounted(() => {
    clearInterval(timer)
    stopCollection() // 停止收集性能指标
    responseTimeChart?.dispose()
    throughputChart?.dispose()
    errorRateChart?.dispose()
    resourceUsageChart?.dispose()
    distributionChart?.dispose()
    bottleneckChart?.dispose()
    cleanup()
  })
})

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 初始化并优化图表
  responseTimeChart = echarts.init(responseTimeChartRef.value)
  optimizeChart(responseTimeChartRef.value, responseTimeChart, {
    throttle: 100,
    debounce: 200
  })
  
  throughputChart = echarts.init(throughputChartRef.value)
  optimizeChart(throughputChartRef.value, throughputChart, {
    throttle: 100,
    debounce: 200
  })
  
  errorRateChart = echarts.init(errorRateChartRef.value)
  optimizeChart(errorRateChartRef.value, errorRateChart, {
    throttle: 100,
    debounce: 200
  })
  
  resourceUsageChart = echarts.init(resourceUsageChartRef.value)
  optimizeChart(resourceUsageChartRef.value, resourceUsageChart, {
    throttle: 100,
    debounce: 200
  })
  
  distributionChart = echarts.init(distributionChartRef.value)
  optimizeChart(distributionChartRef.value, distributionChart, {
    throttle: 100,
    debounce: 200
  })
  
  bottleneckChart = echarts.init(bottleneckChartRef.value)
  optimizeChart(bottleneckChartRef.value, bottleneckChart, {
    throttle: 100,
    debounce: 200
  })
  
  // 设置图表配置
  responseTimeChart.setOption({
    grid: {
      top: 10,
      right: 10,
      bottom: 20,
      left: 40
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '响应时间(ms)'
    },
    series: [
      {
        type: 'line',
        data: [],
        smooth: true,
        showSymbol: false
      }
    ]
  })
  
  throughputChart.setOption({
    grid: {
      top: 10,
      right: 10,
      bottom: 20,
      left: 40
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: 'TPS'
    },
    series: [
      {
        type: 'line',
        data: [],
        smooth: true,
        showSymbol: false
      }
    ]
  })
  
  errorRateChart.setOption({
    grid: {
      top: 10,
      right: 10,
      bottom: 20,
      left: 40
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '错误率(%)'
    },
    series: [
      {
        type: 'line',
        data: [],
        smooth: true,
        showSymbol: false
      }
    ]
  })
  
  resourceUsageChart.setOption({
    grid: {
      top: 10,
      right: 10,
      bottom: 20,
      left: 40
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '使用率(%)'
    },
    series: [
      {
        type: 'line',
        data: [],
        smooth: true,
        showSymbol: false
      }
    ]
  })
  
  distributionChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
  
  bottleneckChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: []
    },
    series: [
      {
        type: 'bar',
        data: []
      }
    ]
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 加载性能数据
const loadPerformanceData = async () => {
  try {
    // 使用缓存加载性能数据
    const [performanceRes, monitorRes, trendRes] = await Promise.all([
      loadDataWithCache('performance', () => getSystemPerformanceData()),
      loadDataWithCache('monitor', () => getSystemMonitorData()),
      loadDataWithCache('trend', () => getSystemTrendData())
    ])
    
    // 更新性能数据
    Object.assign(performance, {
      avgResponseTime: performanceRes.data.avgResponseTime,
      responseTimeTrend: performanceRes.data.responseTimeTrend,
      throughput: performanceRes.data.throughput,
      throughputTrend: performanceRes.data.throughputTrend,
      errorRate: performanceRes.data.errorRate,
      errorRateTrend: performanceRes.data.errorRateTrend,
      resourceUsage: performanceRes.data.resourceUsage,
      resourceUsageTrend: performanceRes.data.resourceUsageTrend
    })
    
    // 更新图表数据
    updateCharts(monitorRes.data, trendRes.data)
  } catch (error) {
    console.error('加载性能数据失败:', error)
    ElMessage.error('加载性能数据失败')
  }
}

// 更新图表数据
const updateCharts = (monitorData, trendData) => {
  // 更新响应时间图表
  responseTimeChart.setOption({
    xAxis: {
      data: trendData.times
    },
    series: [
      {
        data: trendData.responseTimes
      }
    ]
  })
  
  // 更新吞吐量图表
  throughputChart.setOption({
    xAxis: {
      data: trendData.times
    },
    series: [
      {
        data: trendData.throughputs
      }
    ]
  })
  
  // 更新错误率图表
  errorRateChart.setOption({
    xAxis: {
      data: trendData.times
    },
    series: [
      {
        data: trendData.errorRates
      }
    ]
  })
  
  // 更新资源使用率图表
  resourceUsageChart.setOption({
    xAxis: {
      data: trendData.times
    },
    series: [
      {
        data: trendData.resourceUsages
      }
    ]
  })
  
  // 更新系统调用分布图表
  distributionChart.setOption({
    series: [
      {
        data: monitorData.distribution
      }
    ]
  })
  
  // 更新性能瓶颈分析图表
  bottleneckChart.setOption({
    yAxis: {
      data: monitorData.bottlenecks.map(item => item.name)
    },
    series: [
      {
        data: monitorData.bottlenecks.map(item => item.value)
      }
    ]
  })
}

// 加载建议列表
const loadSuggestionList = async () => {
  suggestionLoading.value = true
  try {
    const res = await loadDataWithCache(
      `suggestions-${suggestionPage.value}-${suggestionPageSize.value}`,
      () => getPerformanceSuggestions({
        page: suggestionPage.value,
        pageSize: suggestionPageSize.value
      })
    )
    suggestionList.value = res.data.list
    suggestionTotal.value = res.data.total
  } catch (error) {
    console.error('加载建议列表失败:', error)
    ElMessage.error('加载建议列表失败')
  } finally {
    suggestionLoading.value = false
  }
}

// 应用建议
const handleApplySuggestion = (row) => {
  currentSuggestion.value = row
  applyForm.applyTime = ''
  applyForm.operator = ''
  applyForm.remark = ''
  applySuggestionVisible.value = true
}

// 提交应用建议
const submitApplySuggestion = async () => {
  if (!applyFormRef.value) return
  
  try {
    await applyFormRef.value.validate()
    applying.value = true
    
    await applyPerformanceSuggestion({
      id: currentSuggestion.value.id,
      ...applyForm
    })
    
    ElMessage.success('应用成功')
    applySuggestionVisible.value = false
    loadSuggestionList()
  } catch (error) {
    console.error('应用建议失败:', error)
    ElMessage.error(error.message || '应用建议失败')
  } finally {
    applying.value = false
  }
}

// 导出建议
const handleExportSuggestions = async () => {
  try {
    const res = await exportPerformanceSuggestions({
      page: suggestionPage.value,
      pageSize: suggestionPageSize.value
    })
    
    // 下载文件
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `性能优化建议_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出建议失败:', error)
    ElMessage.error('导出建议失败')
  }
}

// 工具方法
const getResponseTimeTagType = (value) => {
  if (value <= 100) return 'success'
  if (value <= 500) return 'warning'
  return 'danger'
}

const getThroughputTagType = (value) => {
  if (value >= 1000) return 'success'
  if (value >= 500) return 'warning'
  return 'danger'
}

const getErrorRateTagType = (value) => {
  if (value <= 1) return 'success'
  if (value <= 5) return 'warning'
  return 'danger'
}

const getResourceUsageTagType = (value) => {
  if (value <= 60) return 'success'
  if (value <= 80) return 'warning'
  return 'danger'
}

const getTrendClass = (value) => {
  if (value > 0) return 'trend-up'
  if (value < 0) return 'trend-down'
  return ''
}

const getTrendIcon = (value) => {
  if (value > 0) return 'ArrowUp'
  if (value < 0) return 'ArrowDown'
  return ''
}

const getSuggestionTypeTag = (type) => {
  const tagMap = {
    performance: 'warning',
    security: 'danger',
    stability: 'error',
    optimization: 'info'
  }
  return tagMap[type] || ''
}

const getSuggestionTypeLabel = (type) => {
  const labelMap = {
    performance: '性能优化',
    security: '安全加固',
    stability: '稳定性提升',
    optimization: '资源优化'
  }
  return labelMap[type] || type
}

const getPriorityTag = (priority) => {
  const tagMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return tagMap[priority] || ''
}

const getPriorityLabel = (priority) => {
  const labelMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return labelMap[priority] || priority
}

const getImpactStatus = (impact) => {
  if (impact >= 80) return 'exception'
  if (impact >= 50) return 'warning'
  return 'success'
}

const getSuggestionStatusTag = (status) => {
  const tagMap = {
    pending: 'warning',
    processing: 'info',
    completed: 'success',
    rejected: 'info'
  }
  return tagMap[status] || ''
}

const getSuggestionStatusLabel = (status) => {
  const labelMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    rejected: '已拒绝'
  }
  return labelMap[status] || status
}

// 事件处理
const handleResize = () => {
  responseTimeChart?.resize()
  throughputChart?.resize()
  errorRateChart?.resize()
  resourceUsageChart?.resize()
  distributionChart?.resize()
  bottleneckChart?.resize()
}

const handleSuggestionPageSizeChange = (val) => {
  suggestionPageSize.value = val
  loadSuggestionList()
}

const handleSuggestionPageChange = async (val) => {
  suggestionPage.value = val
  await loadSuggestionList()
  // 预加载下一页数据
  preloadNextPageData()
}

const handleRefreshSuggestions = () => {
  loadSuggestionList()
}

const handleViewSuggestionDetail = (row) => {
  currentSuggestion.value = row
  suggestionDetailVisible.value = true
}

// 添加预加载方法
const preloadNextPageData = () => {
  const nextPage = suggestionPage.value + 1
  if (nextPage * suggestionPageSize.value <= suggestionTotal.value) {
    preloadData(
      `suggestions-${nextPage}-${suggestionPageSize.value}`,
      () => getPerformanceSuggestions({
        page: nextPage,
        pageSize: suggestionPageSize.value
      }),
      1
    )
  }
}

// 添加生成报告方法
const handleGenerateReport = async () => {
  reportLoading.value = true
  try {
    currentReport.value = generateReport()
    reportDialogVisible.value = true
  } catch (error) {
    console.error('生成性能报告失败:', error)
    ElMessage.error('生成性能报告失败')
  } finally {
    reportLoading.value = false
  }
}

// 添加导出报告方法
const handleExportReport = () => {
  if (!currentReport.value) return

  try {
    const reportStr = JSON.stringify(currentReport.value, null, 2)
    const blob = new Blob([reportStr], { type: 'application/json' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `性能报告_${new Date().toISOString()}.json`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出性能报告失败:', error)
    ElMessage.error('导出性能报告失败')
  }
}

// 添加工具方法
const getScoreStatus = (score) => {
  if (score >= 80) return 'success'
  if (score >= 60) return 'warning'
  return 'exception'
}

const getRecommendationType = (priority) => {
  const typeMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return typeMap[priority] || 'info'
}
</script>

<style lang="scss" scoped>
.performance-monitor {
  padding: 20px;
  
  .performance-cards {
    margin-bottom: 20px;
    
    .performance-card {
      height: 100%;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .card-content {
        padding: 10px 0;
        
        .metric-chart {
          height: 100px;
          margin-bottom: 10px;
        }
        
        .metric-trend {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: #909399;
          
          .trend-up {
            color: #f56c6c;
          }
          
          .trend-down {
            color: #67c23a;
          }
        }
      }
    }
  }
  
  .performance-charts {
    margin-bottom: 20px;
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .optimization-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-operations {
        .el-button {
          margin-left: 10px;
        }
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.report-section {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .analysis-item {
    margin-bottom: 20px;

    .analysis-title {
      margin-bottom: 10px;
      font-weight: bold;
    }

    .analysis-issues {
      margin-top: 10px;
      color: #f56c6c;

      .issue-title {
        font-weight: bold;
        margin-bottom: 5px;
      }

      ul {
        margin: 0;
        padding-left: 20px;
      }
    }
  }

  .recommendation-impact {
    margin-top: 10px;
  }
}
</style> 